package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx/ziface"
)

type ConnManager struct {
	connections map[uint32]ziface.IConnection
	connLock    sync.RWMutex // 保护连接集合的读写锁
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}

// ADD 添加连接
func (cm *ConnManager) ADD(conn ziface.IConnection) {
	// 加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	cm.connections[conn.GetConnId()] = conn
	fmt.Println("connID = ", conn.GetConnId(), "connection add to ConnManager successfully: conn num = ", cm.Len())
}

// Remove 删除连接
func (cm *ConnManager) Remove(conn ziface.IConnection) {
	// 加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	delete(cm.connections, conn.GetConnId())
	fmt.Println("connID = ", conn.GetConnId(), "removal from ConnManager successfully: conn num = ", cm.Len())
}

// Get 根据connID获取连接
func (cm *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
	// 加读锁
	cm.connLock.RLock()
	defer cm.connLock.RUnlock()

	if conn, ok := cm.connections[connID]; ok {
		return conn, nil
	}
	return nil, errors.New("connection not found")
}

// Len 得到当前连接总数
func (cm *ConnManager) Len() int {
	return len(cm.connections)
}

// ClearConn 清除并终止所有连接
func (cm *ConnManager) ClearConn() {
	// 加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	for connID, conn := range cm.connections {
		conn.Stop()
		delete(cm.connections, connID)
	}
	fmt.Println("clear all connections successfully! conn num = ", cm.Len())
}
